package com.ubs.lingua.buildtool.cs.utils.ant;

import org.apache.commons.logging.Log;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.Project;

/**
 * Listener which sends events to the logging system.
 */
public class AntLogListener implements BuildListener {

    private final Log log;

    /**
     * Construct the listener and assigns the <code>Log<code> instance.
     * @param log the <code>Log<code> instance
     */
    public AntLogListener(final Log log) {
        this.log = log;
    }

    public void buildFinished(final BuildEvent event) {
        final String projectName = event.getProject().getName();
        if (event.getException() != null) {
            log.error("Exception in Ant Build for " + projectName, event.getException());
        }
        log.info("Finished Ant Build for " + projectName);
    }

    public void buildStarted(final BuildEvent event) {
        log.info("Starting Ant Build for " + event.getProject().getName());
    }

    public void messageLogged(final BuildEvent event) {
        switch (event.getPriority()) {
        case Project.MSG_ERR:
            log.error(event.getMessage());
            break;
        case Project.MSG_WARN:
            log.warn(event.getMessage());
            break;
        case Project.MSG_INFO:
            log.info(event.getMessage());
            break;
        case Project.MSG_VERBOSE:
            log.debug(event.getMessage());
            break;
        case Project.MSG_DEBUG:
            log.debug(event.getMessage());
            break;
        default:
            log.error(event.getMessage());
            break;
        }
    }

    public void targetFinished(final BuildEvent event) {
        final String targetName = event.getTarget().getName();
        if (null == event.getException()) {
            log.info("Target \"" + targetName + "\" finished");
        }
        else {
            log.error("Target \"" + targetName + "\" finished with error", event.getException());
        }
    }

    public void targetStarted(final BuildEvent event) {
        log.info("Target \"" + event.getTarget().getName() + "\" started");
    }

    public void taskFinished(final BuildEvent event) {
        final String taskName = event.getTask().getTaskName();
        if (null == event.getException()) {
            log.info("Task \"" + taskName + "\" finished");
        }
        else {
            log.error("Task \"" + taskName + "\" finished with error", event.getException());
        }
    }

    public void taskStarted(final BuildEvent event) {
        log.info("Task \"" + event.getTask().getTaskName() + "\" started");
    }

}
